package com.jiyi.easemob.util;


import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.android.volley.VolleyError;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMConnectionListener;
import com.hyphenate.EMError;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMMessage.ChatType;
import com.hyphenate.chat.EMMessage.Type;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.controller.EaseUI;
import com.hyphenate.easeui.controller.EaseUI.EaseUserProfileProvider;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.model.EaseNotifier.EaseNotificationInfoProvider;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.jiyi.bean.message.Message;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.bean.EasemobGroup;
import com.jiyi.easemob.bean.EasemobUser;
import com.jiyi.easemob.view.EasemobChatActivity;
import com.jiyi.event.HaoYouListEvent;
import com.jiyi.event.MessageListEvent;
import com.jiyi.event.QunZuListEvent;
import com.jiyi.event.RefreshHintEvent;
import com.jiyi.inteface.WebApi;
import com.jiyi.service.MessageService;
import com.jiyi.service.impl.MessageServiceImpl;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.SPUtils;

import org.greenrobot.eventbus.EventBus;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EaseMobHelp {
	private String TAG = EaseMobHelp.class.getSimpleName();
	private static EaseMobHelp instance = null;
	private EMMessageListener globalMsgListener;
	private MyEMConnectionListener globalConnectionListener;
	private List<String> unBlockGroupIdList = new ArrayList<String>();
	private Context context;
	MessageService mMessageService;
	//环信默认密码
	public static final String password = "5189119";

	public synchronized static EaseMobHelp getInstance() {
		if (instance == null) {
			instance = new EaseMobHelp();
		}
		return instance;
	}

	public void init(final Context context) {
		this.context = context;
		mMessageService = new MessageServiceImpl();
		EMOptions options = initChatOptions();
		if (EaseUI.getInstance().init(context, options)) {
		    //debug mode, you'd better set it to false, if you want release your App officially.
		    EMClient.getInstance().setDebugMode(false);
		 // 设置获取头像和昵称的provider
			EaseUI.getInstance().setUserProfileProvider(
					new EaseUserProfileProvider() {

						@Override
						public EaseUser getUser(String username) {
							return getUserInfo(username);
						}
					});
			//设置自定义消息通知
			EaseUI.getInstance().getNotifier().setNotificationInfoProvider(new EaseNotificationInfoProvider() {

				@Override
				public String getTitle(EMMessage message) {
				  //修改标题,这里使用默认
					return null;
				}

				@Override
				public int getSmallIcon(EMMessage message) {
				  //设置小图标，这里为默认
					return R.mipmap.ic_launcher;
				}

				@Override
				public String getDisplayedText(EMMessage message) {
					// 设置状态栏的消息提示，可以根据message的类型做相应提示
					String ticker = EaseCommonUtils.getMessageDigest(message, context);
					if(message.getType() == Type.TXT){
						ticker = ticker.replaceAll("\\[.{2,3}\\]", "[表情]");
					}
					EaseUser user = getUserInfo(message.getFrom());
					if(user != null){
//						if(ClouldChatType.TRUEHEART.equals(message.getStringAttribute("CloudChatType","")))
//						{
//							return "真心话: " + ticker;
//						}
						return getUserInfo(message.getFrom()).getNick() + ": " + ticker;
					}else{
						return message.getFrom() + ": " + ticker;
					}
				}

				@Override
				public String getLatestText(EMMessage message, int fromUsersNum, int messageNum) {
					return null;
//					 return fromUsersNum + "个联系人，发来了" + messageNum + "条消息";
				}

				@Override
				public Intent getLaunchIntent(EMMessage message) {
					//设置点击通知栏跳转事件
					Intent intent = new Intent(context, EasemobChatActivity.class);
					ChatType chatType = message.getChatType();
					if (chatType == ChatType.Chat) { // 单聊信息
						intent.putExtra("name", message.getStringAttribute(ClouldChatType.EASE_CHAT_USER_NICK, ""));
						intent.putExtra("easemobgid", message.getFrom());
						intent.putExtra("easeMobChatType", EaseConstant.CHATTYPE_SINGLE);
						intent.putExtra("memberId", message.getStringAttribute(ClouldChatType.EASE_CHAT_MEMBER_ID, ""));
					} else { // 群聊信息
						// message.getTo()为群聊id
						intent.putExtra("easemobgid", message.getTo());
						intent.putExtra("name", message.getStringAttribute(ClouldChatType.EASE_CHAT_MENBER_NAME, ""));
						if(chatType == ChatType.GroupChat){
							intent.putExtra("easeMobChatType", EaseConstant.CHATTYPE_GROUP);
						}else{
							intent.putExtra("easeMobChatType", EaseConstant.CHATTYPE_CHATROOM);
						}
					}

					//云上聊天类型
					intent.putExtra(ClouldChatType.INTENT_MSG_TP, message.getStringAttribute("CloudChatType", ""));
					//设置清除消息数量标志
					intent.putExtra(ClouldChatType.EASE_CHAT_ISNOTIFYCLEAR, true);
					return intent;
				}
			});
		}

	}

	/**
	 * author hym desc 添加环信全局消息监听 2016-7-28
	 */
	public void addGlobalListener() {
		synchronized (instance) {
			if (null == globalMsgListener) {
				globalMsgListener = msgListener;
				// 注册环信消息接收监听
				EMClient.getInstance().chatManager()
						.addMessageListener(globalMsgListener);
				Log.e("Main", "注册环信消息监听");
			}
			if (null == globalConnectionListener) {
				globalConnectionListener = new MyEMConnectionListener() ;
				//注册一个监听连接状态的listener
				EMClient.getInstance().addConnectionListener(globalConnectionListener);
				Log.e("Main", "注册环信连接状态监听");
			}
		}

	}

	/**
	 * author hym desc 移除环信全局消息监听 2016-7-28
	 */
	public void removeGlobalListener() {
		synchronized (instance) {
			if (null != globalConnectionListener) {
				//注销一个监听连接状态的listener
				EMClient.getInstance().removeConnectionListener(globalConnectionListener);
				Log.e("Main", "注销环信连接状态监听");
				globalConnectionListener = null;
			}

			if (null != globalMsgListener) {
				// 注册环信消息接收监听
				EMClient.getInstance().chatManager()
						.removeMessageListener(globalMsgListener);
				globalMsgListener = null;
				Log.e("Main", "注销环信消息监听");
			}


		}

	}

	/*
	 * 消息接收事件监听
	 */
	EMMessageListener msgListener = new EMMessageListener() {

		@Override
		public void onMessageReceived(List<EMMessage> messages) {
			Log.e("msgListener__________", "--------------收到消息-------------------------");
			for (EMMessage message : messages) {
				// ************接收并处理扩展消息***********************
				// 用户昵称
				String userName = message
						.getStringAttribute("ChatUserNick", "");
				// 用户头像
				String userPic = message.getStringAttribute("ChatUserPic", "");
				// menID
				String memberId = message.getStringAttribute("ChatMemberId", "");
				// 用户名
				String hxIdFrom = message.getFrom();
				// 群环信id
				String groupId = message.getTo();
				// 群组数据库ID
				String jyGroupId = message.getStringAttribute(ClouldChatType.EASE_CHAT_messageId, "");
				// 对方头像
				String receivePic = message.getStringAttribute(ClouldChatType.EASE_CHAT_RECEIVE_PIC, "");
				// 聊天对象 用户就显示用户昵称，群组就显示群组名称
				String menberName = message.getStringAttribute(ClouldChatType.EASE_CHAT_MENBER_NAME, "");

				// 保存用户
				EaseCacheUtil.getInstance().saveEaseMobUser(userName, userPic,
						memberId, hxIdFrom);

				//有设置圈免打扰的不提醒消息或者当前园区与收到的不是同个园区也不提醒
				if (!unBlockGroupIdList.contains(groupId)) {
					// 应用在后台，不需要刷新UI,通知栏提示新消息
					if (!EaseUI.getInstance().hasForegroundActivies()) {
						EaseUI.getInstance().getNotifier().onNewMsg(message);
					}
				}
//				Intent intent = new Intent();
//		    	intent.setAction(Constans.UnRreadMsg);
//		    	context.sendBroadcast(intent);
				Log.e("memberId ", memberId);
				Log.e("chattype ", message.getChatType().ordinal()+1+"");
				//获取消息类型，私聊还是群聊
				int type = message.getChatType().ordinal()+1;
				//根据不同的消息类型去刷新不同的互动时间
				String id = type == 1 ? memberId : jyGroupId;
				// 上传互动时间
				postUpdateTime(id,type);


				/** 保存到本地消息数据库 **/
				//获取消息的归属类型 1：群组 2：活动 3：好友 4：活动 5：话题 6：系统 7：吉友秀 8：商城 9：维保
				String belongType = type == 1 ? "3" : "1";
				//获取消息的类型 1：群邀请成员消息 2：群解散通知 3：退群通知 4：申请入群通知 5：群聊天消息、6：申请好友 7: 好友聊天
				String msgType = belongType.equals("1") ? "5" : "7";
				Message notify = mMessageService.getLastMessageByType(UserInfoUtil.getCurrentUserAccount(),msgType, belongType,type == 1 ? memberId : jyGroupId);
				if (notify == null) {
					notify = new Message();
					notify.setAccount(UserInfoUtil.getCurrentUserAccount());
					notify.setBelongType(Integer.parseInt(belongType));
					notify.setMsgType(Integer.parseInt(msgType));
					notify.setCreateDate(com.swift.utils.DateUtils.fmtDateToStr(new Date(message.getMsgTime()), com.swift.utils.DateUtils.YMDHMS_FORMAT));
					notify.setIsDel(false);
					notify.setIsHandle(false);
					notify.setIsReaded(false);

					Type easeMessageType = message.getType();
					if (Type.TXT.equals(easeMessageType)) {
						EMTextMessageBody body = (EMTextMessageBody) message.getBody();
						String msgTxt = body.getMessage();
						notify.setMsgContent(type == 1 ? msgTxt : userName+":"+msgTxt);
					} else if (Type.IMAGE.equals(easeMessageType)) {
						notify.setMsgContent(type == 1 ? "[图片]" : userName+":"+"[图片]");
					} else if (Type.VOICE.equals(easeMessageType)) {
						notify.setMsgContent(type == 1 ? "[语音]" : userName+":"+"[语音]");
					} else if (Type.LOCATION.equals(easeMessageType)) {
						notify.setMsgContent(type == 1 ? "[位置]" : userName+":"+"[位置]");
					}
					notify.setMsgIcon(type == 1 ? userPic : receivePic);
					notify.setMsgTitle(type == 1 ? userName : menberName);
					//这里需要注意，如果是群组的话，receive_user_id存放的是发送的用户人的id
					notify.setReceive_user_id(type == 1 ? UserInfoUtil.getCurrentUserId()+"" : memberId);
					notify.setReceive_easemob_id(type == 1 ? UserInfoUtil.getCurrentUserAccount() : hxIdFrom);
					notify.setSend_user_id(type == 1 ? memberId : jyGroupId);
					notify.setSend_easemob_id(type == 1 ? hxIdFrom : groupId);

					notify.save();
				}
				else {
					notify.setAccount(UserInfoUtil.getCurrentUserAccount());
					notify.setBelongType(Integer.parseInt(belongType));
					notify.setMsgType(Integer.parseInt(msgType));
					notify.setCreateDate(com.swift.utils.DateUtils.fmtDateToStr(new Date(message.getMsgTime()), com.swift.utils.DateUtils.YMDHMS_FORMAT));
					notify.setIsDel(false);
					notify.setIsHandle(false);
					notify.setIsReaded(false);

					Type easeMessageType = message.getType();
					if (Type.TXT.equals(easeMessageType)) {
						EMTextMessageBody body = (EMTextMessageBody) message.getBody();
						String msgTxt = body.getMessage();
						notify.setMsgContent(type == 1 ? msgTxt : userName+":"+msgTxt);
					} else if (Type.IMAGE.equals(easeMessageType)) {
						notify.setMsgContent(type == 1 ? "[图片]" : userName+":"+"[图片]");
					} else if (Type.VOICE.equals(easeMessageType)) {
						notify.setMsgContent(type == 1 ? "[语音]" : userName+":"+"[语音]");
					} else if (Type.LOCATION.equals(easeMessageType)) {
						notify.setMsgContent(type == 1 ? "[位置]" : userName+":"+"[位置]");
					}
					notify.setMsgIcon(type == 1 ? userPic : receivePic);
					notify.setMsgTitle(type == 1 ? userName : menberName);
					//这里需要注意，如果是群组的话，receive_user_id存放的是发送的用户人的id
					notify.setReceive_user_id(type == 1 ? UserInfoUtil.getCurrentUserId()+"" : memberId);
					notify.setReceive_easemob_id(type == 1 ? UserInfoUtil.getCurrentUserAccount() : hxIdFrom);
					notify.setSend_user_id(type == 1 ? memberId : jyGroupId);
					notify.setSend_easemob_id(type == 1 ? hxIdFrom : groupId);
					notify.update(notify.getId());
				}


				//刷新红点
				EventBus.getDefault().post(new RefreshHintEvent(RefreshHintEvent.MIME));
				//刷新消息列表
				EventBus.getDefault().post(new MessageListEvent(MessageListEvent.MY_MESSAGE));
			}
		}

		@Override
		public void onCmdMessageReceived(List<EMMessage> messages) {
			// 收到透传消息
		}

		@Override
		public void onMessageReadAckReceived(List<EMMessage> messages) {
			// 收到已读回执
		}

		@Override
		public void onMessageDeliveryAckReceived(List<EMMessage> message) {
			// 收到已送达回执
		}

		@Override
		public void onMessageChanged(EMMessage message, Object change) {
			// 消息状态变动
		}
	};

	/**
	 * author hym desc 初始化环信配置 2016-7-29
	 *
	 * @return
	 */
	private EMOptions initChatOptions() {
		Log.d(TAG, "init HuanXin Options");

		EMOptions options = new EMOptions();
		// set if accept the invitation automatically
		options.setAcceptInvitationAlways(false);
		// set if you need read ack
		options.setRequireAck(true);
		// set if you need delivery ack
		options.setRequireDeliveryAck(false);

		// you need apply & set your own id if you want to use google cloud
		// messaging.
		// options.setGCMNumber("324169311137");
		// you need apply & set your own id if you want to use Mi push
		// notification
		// options.setMipushConfig("2882303761517426801", "5381742660801");
		// you need apply & set your own id if you want to use Huawei push
		// notification
		// options.setHuaweiPushAppId("10492024");

		// options.allowChatroomOwnerLeave(getModel().isChatroomOwnerLeaveAllowed());
		// options.setDeleteMessagesAsExitGroup(getModel().isDeleteMessagesAsExitGroup());
		// options.setAutoAcceptGroupInvitation(getModel().isAutoAcceptGroupInvitation());

		return options;
	}

	private EaseUser getUserInfo(String username) {
		// To get instance of EaseUser, here we get it from the user list in
		// memory
		// You'd better cache it if you get it from your server
		EaseUser user = null;

		// 获取环信id的用户
		EasemobUser easemobUser = EaseCacheUtil.getInstance().getEaseMobUser(
				username);
		if (null != easemobUser) {
			user = new EaseUser(username);
			convertEaseUser(user, easemobUser);
		}

		// if user is not in your contacts, set inital letter for him/her
		if (user == null) {
			user = new EaseUser(username);
			EaseCommonUtils.setUserInitialLetter(user);
		}
		return user;
	}

	/**
	 * author hym desc 环信用户登录 2016-7-26
	 *
	 * @param userName
	 * @param password
	 */
	public void login(String userName, String password) {
		//如果已经登录过，先退出
		logout();
		EMClient.getInstance().login(userName, password, new EMCallBack() {// 回调
					@Override
					public void onSuccess() {
						EMClient.getInstance().groupManager().loadAllGroups();
						EMClient.getInstance().chatManager()
								.loadAllConversations();
						Log.e("main", "登录聊天服务器成功！");
						Log.e("current ", EMClient.getInstance().getCurrentUser());
					}

					@Override
					public void onProgress(int progress, String status) {

					}

					@Override
					public void onError(int code, String message) {
						Log.d("main", "登录聊天服务器失败！");
					}
				});
	}

	/**
	 * author hym desc 环信用户退出 2016-7-26
	 */
	public void logout() {
		if(EMClient.getInstance().isLoggedInBefore()){
			Log.e("main", "退出环信登录！");
			EMClient.getInstance().logout(true);
        }
	}

	/**
	 * author hym desc 自定义用户转换成环信的用户 2016-7-27
	 *
	 * @param easeUser
	 * @param easemobUser
	 */
	public static void convertEaseUser(EaseUser easeUser,
			EasemobUser easemobUser) {
		easeUser.setAvatar(easemobUser.getAvatar());
		easeUser.setNick(easemobUser.getNickName());
	}


	/**
	 * author hym
	 * desc 添加免打扰的圈id
	 * 2016-8-2
	 * @param groupid
	 */
	public synchronized void addUnBlockGroupId(String groupid)
	{
		if (!unBlockGroupIdList.contains(groupid)) {
			//保存到数据库
			EasemobGroup easemobGroup = DataSupport.where("groupId = ? and easeUid = ?",groupid,SPUtils.getInstance().get("mobile", "").toString()).findFirst(EasemobGroup.class);
			if (null == easemobGroup) {
				easemobGroup = new EasemobGroup();
			}
			easemobGroup.setIsUnBlock(true);
			easemobGroup.setEaseUid(SPUtils.getInstance().get("mobile", "").toString());
			easemobGroup.setGroupId(groupid);
			easemobGroup.save();

			//保存到缓存
			unBlockGroupIdList.add(groupid);
		}



	}

	/**
	 * author hym
	 * desc 删除免打扰的圈id
	 * 2016-8-2
	 * @param groupid
	 */
	public synchronized void removeUnBlockGroupId(String groupid)
	{
		if (unBlockGroupIdList.contains(groupid)) {
			//修改数据库
			EasemobGroup easemobGroup = DataSupport.where("groupId = ? and easeUid = ?",groupid,SPUtils.getInstance().get("mobile", "").toString()).findFirst(EasemobGroup.class);
			if (null != easemobGroup) {
				easemobGroup.setIsUnBlock(false);
				easemobGroup.save();
			}

			//删除缓存
			unBlockGroupIdList.remove(groupid);
		}
	}

	/**
	 * author hym
	 * desc 初始化免打扰的圈id
	 * 2016-8-2
	 */
	public void initUnBlockGroupId()
	{
		//清除缓存
		unBlockGroupIdList.clear();
		//查询数据库某个用户的圈设置了免打扰信息的数据
		List<EasemobGroup> easemobGroupList = DataSupport.where("easeUid = ? and isUnBlock = ?",SPUtils.getInstance().get("mobile", "").toString(),"1").find(EasemobGroup.class);
		if (null != easemobGroupList && easemobGroupList.size()>0) {
			//遍历数据库，把设置了免打扰的圈保存的缓存上
			for (EasemobGroup easemobGroup : easemobGroupList) {
				if (!unBlockGroupIdList.contains(easemobGroup.getGroupId())) {
					unBlockGroupIdList.add(easemobGroup.getGroupId());
				}
			}
		}
	}

	//实现ConnectionListener接口
	private class MyEMConnectionListener implements EMConnectionListener {
	    @Override
		public void onConnected() {
		}
	    @Override
        public void onDisconnected(int error) {
            if (error == EMError.USER_REMOVED) {
                //环信账号被删除
            }else if (error == EMError.USER_LOGIN_ANOTHER_DEVICE) {
            	UserHelp.getInstance().clearUser(context);
            }
        }
	}

	void postUpdateTime(String id,final int chatType) {
		Map<String, String> params = new HashMap<String, String>();
		params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
		params.put("id", id);
		params.put("type", (chatType == EaseConstant.CHATTYPE_SINGLE ? EaseConstant.CHATTYPE_SINGLE : EaseConstant.CHATTYPE_GROUP)+"");

		VolleyRequest.StringRequestPost(AppBase.Context,
				WebApi.ZONE_HAOYOU_ACCESS_TIME, "", params,
				new StringInterface(AppBase.Context) {

					@Override
					public void stringSuccess(String result) {
						Log.e("postUpdateTime ", result);
						if (chatType == EaseConstant.CHATTYPE_SINGLE) {
							EventBus.getDefault().postSticky(new HaoYouListEvent(HaoYouListEvent.MY_HAOYOU_FRAGMENT));
						}
						else {
							EventBus.getDefault().postSticky(new QunZuListEvent(QunZuListEvent.MY_QUNZU_FRAGMENT));
						}
					}

					@Override
					public void stringError(VolleyError error) {
						Log.e("postUpdateTime ", error.getMessage());
					}
				});
	}

}
